package com.hxzy.controller.anonymous.captcha;

import com.hxzy.common.constants.RedisConstants;
import com.hxzy.common.resp.R;
import com.wf.captcha.ArithmeticCaptcha;
import com.wf.captcha.GifCaptcha;
import com.wf.captcha.SpecCaptcha;
import com.wf.captcha.base.Captcha;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Api(tags = "匿名-验证码Api")
@RestController
@RequestMapping(value = "/anony/captcha")
public class CaptchaController {


    @Autowired
    private RedisTemplate redisTemplate;


    @ApiOperation(value = "英文字母验证码")
    @GetMapping(value = "/png")
    public R  pngCaptcha(@RequestParam(defaultValue = "150") Integer width,
                         @RequestParam(defaultValue = "50")Integer height,
                         @RequestParam(defaultValue = "4")Integer len){
        SpecCaptcha captcha = new SpecCaptcha(width,height,len);
        return createCaptcha(captcha);

    }

    @ApiOperation(value = "gif字母验证码")
    @GetMapping(value = "/gif")
    public R  gifCaptcha(@RequestParam(defaultValue = "150") Integer width,
                         @RequestParam(defaultValue = "50")Integer height,
                         @RequestParam(defaultValue = "4")Integer len){
        GifCaptcha captcha = new GifCaptcha(width,height,len);
        return createCaptcha(captcha);

    }

    @ApiOperation(value = "算术运算验证码")
    @GetMapping(value = "/airth")
    public R  airthCaptcha(@RequestParam(defaultValue = "150") Integer width,
                         @RequestParam(defaultValue = "50")Integer height,
                         @RequestParam(defaultValue = "2")Integer len){
        ArithmeticCaptcha captcha = new ArithmeticCaptcha(width,height,len);
        return createCaptcha(captcha);

    }

    private R  createCaptcha(Captcha  captcha){
        String value=captcha.text();

        String imgStr=captcha.toBase64();

        String uuid=  UUID.randomUUID().toString();

        String redisKey= RedisConstants.CAPTCHA_PREFIX+uuid;

        this.redisTemplate.opsForValue().set(redisKey,value,RedisConstants.CAPTCHA_EXPIRED_MINUTES, TimeUnit.MINUTES);

        Map<String,String>  dataMap=new HashMap<>();
        dataMap.put("uuid",uuid);
        dataMap.put("image",imgStr);
        return R.okHasData(dataMap);
    }


}
